﻿namespace SuperModel.Behaviors
{
    using System.Linq;
    using BehaviorModel;
    using Castle.Core.Interceptor;

    /// <summary>
    /// A property-set filter to declare property-checking behavior.  
    /// If we're checking and property is different, the invocation will proceed.
    /// </summary>
    public class CheckIfPropertyChanged : BaseSetFilter
    {
        /// <summary>
        /// Perform the Invocation
        /// </summary>
        /// <param name="invocation">
        /// The invocation.
        /// </param>
        /// <returns>
        /// A value indicating whether or not to proceed
        /// </returns>
        protected override bool ExecuteInternal(IInvocation invocation)
        {
            // If the invocation is trivial or we're not checking the property, pass through
            if (invocation.Arguments == null || invocation.Arguments.Count() == 0)
            {
                return true;
            }

            // Verify that the argument is different than the property
            object argument = invocation.Arguments[0];
            object value = invocation.TargetType.GetProperty(PropertyName).GetValue(invocation.InvocationTarget, null);
            if (argument == null)
            {
                return value != null;
            }

            return !argument.Equals(value);
        }
    }
}